import re
from _testcapi import raise_exception

import jwt
from django.contrib.auth.backends import ModelBackend
from rest_framework import mixins, viewsets, HTTP_HEADER_ENCODING
from rest_framework.authentication import get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.utils import jwt_decode_handler

from user.models import UserProfile

from user.utils import get_jwt_by_user


class JWTModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r'1[3-9]\d{9}$',username):#shouji
                user = UserProfile.objects.get(mobile=username)
            elif re.match(r'.*@.*',username):
                user = UserProfile.objects.get(email=username)
            else:
                user = UserProfile.objects.get(username=username)
        except UserProfile.DoesNotExist:
            return None# 认证失败就返回None即可，jwt就无法删除token
        # 用户存在，密码校验通过，是活着的用户 is_active字段为1
        # if user and user.check_password(password) and self.user_can_authenticate(user):
        if user and user.password == password and self.user_can_authenticate(user):
            return user  # 认证通过返回用户，交给jwt生成token


class JsonWebTokenAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = get_authorization_header(request)
        if not jwt_value:
            raise AuthenticationFailed('Authorization 字段是必须的')
        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('签名过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法用户')
        user = self.authenticate_credentials(payload)

        return user, jwt_value



